package kr.ragne.framework;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class GameView extends SurfaceView implements SurfaceHolder.Callback{
	private GameViewThread mThread;
	private IState mState;

	public GameView(Context context) {
		super(context);
		getHolder().addCallback(this);
		mThread = new GameViewThread(getHolder(), this);
		
		AppManager.getInstance().setmGameView(this);
		AppManager.getInstance().setmResources(getResources());
		
		ChangeGameState(new TestState());
	}
	
	@Override
	public void draw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		mState.Render(canvas);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// 스레드를 실행 상태로 만듬
		mThread.setRunning(true);
		// 스레드 실행
		mThread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		mThread.setRunning(false);
		while(retry){
			try{
				mThread.join();
				retry = false;
			}catch(InterruptedException e){
				//스레드가 종료되도록 계속 시도
			}
		}
	}
	
	public void Update(){
		mState.Update();
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		mState.onKeyDown(keyCode, event);
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		mState.onTouchEvent(event);
		return super.onTouchEvent(event);
	}
	
	public void ChangeGameState(IState state){
		if(mState != null)
			mState.Destroy();
		state.Init();
		mState = state;
	}
}
